package com.nacos.druid;

import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.nacos.concifg.DataBase;
import com.nacos.concifg.DataBaseConfig;
import com.nacos.concifg.DataBaseConfig1;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

public class DynamicDataSourceConf {

    @Autowired
    DataBaseConfig dataBaseConfig;

    @Autowired
    DataBaseConfig1 dataBaseConfig1;

    @Bean
    @Primary
    public DynamicDataSource dynamicDataSource() {
        Map<Object, Object> targetDataSources = new HashMap<>(2);

        // 检查第一个数据源
        DataBase dataBase = dataBaseConfig.getDataBase();
        checkDataSource(dataBase, "test");
        targetDataSources.put("test", dataBase);

        // 检查第二个数据源
        DataBase dataBase1 = dataBaseConfig1.getDataBase();
        checkDataSource(dataBase1, "test1");
        targetDataSources.put("test1", dataBase1);

        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        dynamicDataSource.setTargetDataSources(targetDataSources);

        // 设置默认数据源（如果需要）
        // dynamicDataSource.setDefaultTargetDataSource(dataSource1);

        return dynamicDataSource;
    }

    private void checkDataSource(AbstractRoutingDataSource dataSource, String dataSourceName) {
        try (Connection connection = dataSource.getConnection()) {
            System.out.println(dataSourceName + " 数据源连接正常");
        } catch (SQLException e) {
            throw new RuntimeException(dataSourceName + " 数据源连接异常: " + e.getMessage(), e);
        }
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        // ... 其他配置 ...
        return sqlSessionFactoryBean.getObject();
    }

    // 假设的DynamicDataSource类（你可能已经有这个类了）
    // class DynamicDataSource extends AbstractRoutingDataSource { ... }

    // DataBaseConfig 和 DataBaseConfig1 是配置数据源的类
    // 假设它们有一个getDataBase()方法返回DataSource实例
}